package iotwisp.school.api.controller.pc_admin.user;

import java.util.ArrayList;
import java.util.List;

import iotwisp.school.api.dto.AuthorityDTO;
import iotwisp.school.api.dto.AuthorityItemDTO;
import iotwisp.school.api.dto.MenuDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import iotwisp.base.cqrs.BaseQO;
import iotwisp.base.cqrs.BusinessException;
import iotwisp.base.orm.query.pagination.Pagination;
import iotwisp.base.rest.JSONResultDTO;
import iotwisp.base.rest.RestBaseController;
import iotwisp.base.util.ValidationUtils;
import iotwisp.school.user.command.admin.AdminLoginSCmd;
import iotwisp.school.user.command.admin.AdminLogoutSCmd;
import iotwisp.school.user.command.admin.ChangeAdminEnableSCmd;
import iotwisp.school.user.command.admin.CreateAdminSCmd;
import iotwisp.school.user.command.admin.ModifyAdminSCmd;
import iotwisp.school.user.entity.Admin;
import iotwisp.school.user.entity.AdminMenu;
import iotwisp.school.user.entity.ApiOperate;
import iotwisp.school.user.entity.LoginToken;
import iotwisp.school.user.entity.Role;
import iotwisp.school.user.qo.AdminMenuQO;
import iotwisp.school.user.qo.AdminQO;
import iotwisp.school.user.qo.ApiOperateQO;
import iotwisp.school.user.service.AdminMenuService;
import iotwisp.school.user.service.AdminService;
import iotwisp.school.user.service.ApiOperateService;
import iotwisp.school.user.service.PermissionService;

@RestController
@RequestMapping("/api/org/admin")
public class AdminController extends RestBaseController {

	@Autowired
	private AdminService adminService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private AdminMenuService adminMenuService;
	@Autowired
	private ApiOperateService apiOperateService;

	@PostMapping("/query")
	public ResponseEntity<JSONResultDTO> queryAdmin(@RequestBody AdminQO qo) {

		if (qo.getFetchRoles()) {
			qo.setBatchResult(true);
		}
		switch (qo.getResultType()) {
		case AdminQO.RESULT_TYPE_COUNT:
			Integer count = adminService.queryCount(qo);
			return ResponseEntity.ok(createSuccessResult(count));
		case AdminQO.RESULT_TYPE_UNIQUE:
			Admin admin = adminService.queryUnique(qo);
			List<Admin> list = new ArrayList<>();
			list.add(admin);
			list = handleData(list, qo.getDataUseScene());
			return ResponseEntity.ok(createSuccessResult(list.get(0)));
		case AdminQO.RESULT_TYPE_LIST:
			List<Admin> admins = adminService.queryList(qo);
			handleData(admins, qo.getDataUseScene());
			return ResponseEntity.ok(createSuccessResult(admins));
		case AdminQO.RESULT_TYPE_PAGINATION:
			Pagination pagination = adminService.queryPagination(qo);
			List<Admin> adminList = (List<Admin>) pagination.getList();
			adminList = handleData(adminList, qo.getDataUseScene());
			pagination.setList(adminList);
			return ResponseEntity.ok(createSuccessResult(pagination));
		default:
			return ResponseEntity.badRequest()
					.body(createFailResult(BusinessException.NECESSARY_PARAM_NULL, "resultType值有误", null));
		}

	}

	private List<Admin> handleData(List<Admin> admins, String dataUseScene) {
		switch (dataUseScene) {
		case "admin_admin_list":
			for (Admin admin : admins) {
				admin.setRoleSet(null);
			}
			break;
		case "admin_center":

			break;
		default:
			for (Admin admin : admins) {
				for (Role role : admin.getRoleSet()) {
					role.setAdminSet(null);
					role.setPermissionSet(null);
				}
			}
			break;
		}
		return admins;
	}

	@PostMapping("/authority/query")
	public ResponseEntity<JSONResultDTO> queryAuthority() {

		ApiOperateQO apiOperateQO = new ApiOperateQO();
		apiOperateQO.setResultType("list");
		apiOperateQO.setOrderByLeftValue(BaseQO.ORDER_ASC);
		List<ApiOperate> apiOperates = apiOperateService.queryList(apiOperateQO);

		List<AuthorityItemDTO> authorities = new ArrayList<>();
		for (int i = 1; i <= apiOperates.size(); i++) {
			AuthorityItemDTO authorityItemDTO = transApiOperate(apiOperates.get(i - 1));
			authorityItemDTO.setAuthority_id(i);
			authorities.add(authorityItemDTO);
		}
//        for (ApiOperate apiOperate : apiOperates) {
//            AuthorityItemDTO authorityItemDTO = transApiOperate(apiOperate);
//            authorities.add(authorityItemDTO);
//        }

		AdminMenuQO adminMenuQO = new AdminMenuQO();
		adminMenuQO.setResultType("list");
		adminMenuQO.setOrderByLeftValue(BaseQO.ORDER_ASC);
		List<AdminMenu> adminMenus = adminMenuService.queryList(adminMenuQO);

		List<MenuDTO> menus = new ArrayList<>();
		for (int i = 1; i <= adminMenus.size(); i++) {
			MenuDTO menuDTO = transAdminMenu(adminMenus.get(i - 1));
			menuDTO.setMenuId(i);
			menus.add(menuDTO);
		}
//        for (AdminMenu adminMenu : adminMenus) {
//            MenuDTO menuDTO = transAdminMenu(adminMenu);
//            menus.add(menuDTO);
//        }

		AuthorityDTO authorityDTO = new AuthorityDTO();
		authorityDTO.setMenus(menus);
		authorityDTO.setAuthorities(authorities);

		return ResponseEntity.ok(createSuccessResult(authorityDTO));
	}

	private AuthorityItemDTO transApiOperate(ApiOperate apiOperate) {

		AuthorityItemDTO authorityItemDTO = new AuthorityItemDTO();
//        authorityItemDTO.setAuthority_id(apiOperate.getId());
		authorityItemDTO.setAuthority_code(apiOperate.getId());
		authorityItemDTO.setAuthority_name(apiOperate.getName());
		return authorityItemDTO;
	}

	private MenuDTO transAdminMenu(AdminMenu adminMenu) {
		MenuDTO menuDTO = new MenuDTO();
//        menuDTO.setMenuId(adminMenu.getId());
		menuDTO.setIcon(adminMenu.getIcon());
		menuDTO.setLink(adminMenu.getLink());
		menuDTO.setDepth(adminMenu.getTreeData().getLevel());
		menuDTO.setRgt(adminMenu.getTreeData().getRightValue());
		menuDTO.setLft(adminMenu.getTreeData().getLeftValue());
		menuDTO.setMenuName(adminMenu.getName());
		menuDTO.setMenuCode(adminMenu.getCode());
		return menuDTO;
	}

	@PostMapping("/create")
	public ResponseEntity<JSONResultDTO> createAdmin(@RequestBody CreateAdminSCmd cmd) throws BusinessException {
		ValidationUtils.validate(cmd);
		Admin admin = adminService.createAdmin(cmd);
		return ResponseEntity.ok(createSuccessResult(admin));
	}

	@PutMapping("/modify")
	public ResponseEntity<JSONResultDTO> modifyAdmin(@RequestBody ModifyAdminSCmd cmd) throws BusinessException {
		ValidationUtils.validate(cmd);
		Admin admin = adminService.modifyAdmin(cmd);
		return ResponseEntity.ok(createSuccessResult(admin));
	}

	@PutMapping("/change_enable")
	public ResponseEntity<JSONResultDTO> changeAdminEnable(@RequestBody ChangeAdminEnableSCmd cmd) {

		adminService.changeAdminEnable(cmd);
		return ResponseEntity.ok(createSuccessResult(null));
	}

	@PostMapping("/login")
	public ResponseEntity<JSONResultDTO> adminLogin(@RequestBody AdminLoginSCmd cmd) throws BusinessException {

		LoginToken loginToken = adminService.adminLogin(cmd);
		return ResponseEntity.ok(createSuccessResult(loginToken));
	}

	@PostMapping("/logout")
	public ResponseEntity<JSONResultDTO> adminLogout(@RequestBody AdminLogoutSCmd cmd) throws BusinessException {

		adminService.adminLogout(cmd);
		return ResponseEntity.ok(createSuccessResult(null));
	}
}
